<template>
  <ProTable
    ref="tableRef"
    :fetchListApi="getBroadcastList"
    :columns="columns"
    row-key="id"
    :rowSelection="rowSelection"
  >
    <template #toolbars>
      <Space>
        <b-button icon="add" code="broadcastManage:add" @click="onAdd()"
          >新增</b-button
        >
        <b-button
          icon="delete"
          code="broadcastManage:del"
          :disabled="!selectRows.length"
          @click="onDelete()"
          >删除
        </b-button>
      </Space>
    </template>
    <template #operation="{ record }">
      <template v-if="record.isAudit != '0'">
        <b-button
          icon="detail"
          type="link"
          code="broadcastManage:query"
          @click="onDetail(record)"
          >详情</b-button
        >
        <!-- <b-button
          type="link"
          v-hasPermi="['packageManage:audit']"
          @click="onAudit(record)"
        >
          审核</b-button
        > -->
      </template>
      <b-button
        icon="remote"
        code="broadcastManage:pull"
        type="link"
        @click="handlePush(record)"
        >推送</b-button
      >
      <b-button
        icon="delete"
        type="link"
        code="broadcastManage:del"
        @click="onDelete(record)"
        >删除
      </b-button>
    </template>
  </ProTable>
  <FormModal :items="items">
    <!--   accept='.cer' -->
  </FormModal>

  <Modal
    title="推送"
    v-model:open="pushConfigVisible"
    :width="1600"
    :mask-closable="false"
    :keyboard="false"
    :footer="null"
    centered
    destroy-on-close
  >
    <PushConfig
      :page-data="pageDate"
      @pushSuccess="pushSuccess"
      @close="pushConfigVisible = false"
    />
  </Modal>

  <Modal
    :title="failTitle"
    v-model:open="pushDeviceVisible"
    :width="1400"
    :mask-closable="false"
    :keyboard="false"
    :footer="null"
    centered
    destroy-on-close
  >
    <PushDevice :page-data="pushDeviceData" />
  </Modal>
</template>

<script setup lang="tsx">
import { computed, onMounted, ref } from 'vue';
import {
  Modal,
  Radio,
  RadioGroup,
  Space,
  Tag,
  Tree,
  TreeProps,
  TreeSelect,
  Upload,
  type UploadChangeParam,
  type UploadProps,
  message,
} from 'ant-design-vue';
import { ProFormProps } from '@/components/ProForm';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { useFormModal } from '@/hooks/formModal';
import { download, hasOwnProperty, listToEnum } from '@/utils/utils';
import {
  auditEnum,
  deviceTypeEnum,
  deviceTypeOption,
  picUseTypeEnum,
} from '@/constant/push';
import { getProjectData } from '@/api/config';
import {
  addBroadcast,
  broadcastManage,
  delBroadcast,
  getBroadcastList,
  getDataListInfo,
  uploadFile,
} from '@/api/push';
import PushConfig from '../components/PushConfig.vue';
import PushDevice from '../components/PushDevice.vue';

const tableRef = ref();

const projectData = ref([]);
onMounted(() => {
  getProjectData().then((res: any) => {
    projectData.value = res.data;
    addDisableProperty(projectData.value);
  });
});
const selectRows = ref<any[]>([]);
const rowSelection = computed<ProTableProps['rowSelection']>(() => {
  return {
    onChange(values, selectedRows) {
      selectRows.value = selectedRows;
    },
  };
});
const _getUpgradeList = async (params: any) => {
  const res = await getDataListInfo({ ...params, type: '4' });
  return { rows: [...res.rows], total: res.total || 0 };
};
const addDisableProperty = (tree: any) => {
  tree.forEach((item: any) => {
    if (item.type === '1') {
      item.disabled = true;
      item.selectable = false;
    }
    if (item.children) {
      addDisableProperty(item.children);
    }
  });
};
const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '资料编码',
    dataIndex: 'code',
  },
  {
    title: '标题',
    dataIndex: 'title',
    hideInSearch: true,
  },

  {
    title: '创建人',
    hideInSearch: true,
    dataIndex: 'createBy',
  },
  {
    title: '创建时间',
    width: 150,
    isTime: true,
    dataIndex: 'createTime',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    width: 220,
  },
]);
const items = computed<ProFormProps['items']>(() => [
  // {
  //   label: '资料描述',
  //   type: 'textarea',
  //   field: 'dataDesc',
  //   rules: [
  //     {
  //       required: true,
  //       message: '请输入资料描述',
  //       trigger: 'blur',
  //     },
  //   ],
  // },
  {
    label: '所属项目',
    type: 'input',
    field: 'projectId',
    rules: [
      {
        required: true,
        message: '请输入所属项目',
        trigger: 'blur',
      },
    ],
    customRender(formState) {
      return (
        <TreeSelect
          v-model:value={formState.projectId}
          fieldNames={{
            children: 'children',
            label: 'label',
            value: 'id',
          }}
          placeholder='请选择'
          allowClear={true}
          treeNodeFilterProp='disabled'
          treeData={projectData.value.map((item) => ({
            // Changed from :treeData to treeData
            ...item,
            disabled: item.type == 1,
          }))}
        />
      );
    },
  },
  {
    label: '标题',
    type: 'input',
    field: 'title',
    rules: [
      {
        required: true,
        message: '请输入标题',
        trigger: 'blur',
      },
    ],
  },
  {
    label: '内容',
    type: 'input',
    field: 'msg',
    rules: [
      {
        required: true,
        message: '请输入内容',
        trigger: 'blur',
      },
    ],
  },
]);
const { FormModal, open, formRef } = useFormModal({
  size: 'middle',
  column: 2,
  formProps: { labelCol: { span: 4 } },
  // onValuesChange(changeValues, formState) {
  //   if (hasOwnProperty(changeValues, 'deviceType')) {
  //     const { deviceType } = changeValues;
  //     if (deviceType == '3') {
  //       formState.subType = '3';
  //     } else {
  //       formState.subType = '1';
  //     }
  //   }
  // },
});

const uploadImg = ref('');

const onAdd = async () => {
  open({
    title: '新增',
    defaultValue: {},
    serviceApi: async (params: any): Promise<any> => {
      await addBroadcast({
        ...params,
        type: '1',
      });
      sleep(() => tableRef.value.refresh());
    },
  });
};

const onDetail = async (record: any) => {
  open({
    title: '详情',
    modalType: 'info',
    defaultValue: { ...record },
    hasEditPermission: false,
    serviceApi: () => Promise.resolve(''),
  });
};
const onAudit = async (record: any) => {
  Modal.confirm({
    title: '系统提示',
    centered: true,
    content: `确认审核通过？`,
    onOk: async () => {
      await packageAudit({ upgradeId: record.upgradeId, isAudit: '0' });
      sleep(() => tableRef.value.refresh());
      message.success('审核成功');
    },
  });
};

const sleep = (cb) => {
  setTimeout(() => {
    cb();
  }, 500);
};

const onDelete = async (record: any) => {
  console.log(record, 'record');

  const ids = record
    ? record.id
    : selectRows.value.map((item) => item.id).join();
  Modal.confirm({
    title: '系统提示',
    centered: true,
    content: `确认删除当前项？`,
    onOk: async () => {
      await delBroadcast(ids);
      sleep(() => tableRef.value.refresh());
      message.success('删除成功');
    },
  });
};

const pageDate: any = ref({});
const failTitle: any = ref('');
const pushDeviceData: any = ref({});
const pushDeviceVisible = ref(false);
const pushConfigVisible = ref(false);

const handlePush = (record: any) => {
  console.log(record, 'pageDatepageDate');
  record.dataManageId = record.id;
  record.type = '2';
  pageDate.value = record;
  pushConfigVisible.value = true;
};

const pushSuccess = (row: any) => {
  sleep(() => tableRef.value.refresh());
  pushConfigVisible.value = false;
  pushDeviceData.value = row;
  failTitle.value = '推送结果';
  pushDeviceVisible.value = true;
};
</script>
